#include "edge.h"
#include "face.h"
#include "loop.h"
#include "vertex.h"
#include <GL/gl.h>

Edge::Edge(int _id, HalfEdge *_he1, HalfEdge *_he2) : id(_id), selected(false), he1(_he1), he2(_he2){}

Edge::~Edge()
{
    /**
        deleta suas halfedges
    */
    if(he1) delete he1;
    if(he1) delete he2;
}

void Edge::draw() const
{
    /**
        desenha uma linha dos vertex das halfedges
    */

    Vertex *v1 = he1->getVertex();
    Vertex *v2 = he2->getVertex();
    Color color1 = v1->getColor();
    Color color2 = v2->getColor();
    Color color_;
    if(selected)
    {
        glLineWidth(3);
        color_ = Color(1, 0.0, 0.0, 1);
    }
    else if( ((color1.red <= 0.2) && (color1.green <= 0.2) && (color1.blue <= 0.2)) ||
        ((color2.red <= 0.2) && (color2.green <= 0.2) && (color2.blue <= 0.2)) )
            color_ = Color(1, 1, 1, 1);
    else color_ = Color(0.2, 0.2, 0.2, 1);

    glColor3f(color_.red, color_.green, color_.blue);
    glBegin(GL_LINES);
        glVertex3dv(v1->getPosition().intoVector());
        glVertex3dv(v2->getPosition().intoVector());
    glEnd();

    glLineWidth(1);
}

//void Edge::translate(const Vector3D &_t)
//{
//    he1->getVertex()->translate(_t);
//    he2->getVertex()->translate(_t);
//}

std::set<Vertex *> Edge::getVertices()
{
    std::set<Vertex *> result;
    result.insert(he1->getVertex());
    result.insert(he2->getVertex());

    return result;
}

void Edge::setColor(const Color &_color)
{
    /**
        muda a cor dos dois vertices
    */
    he1->getVertex()->setColor(_color);
    he2->getVertex()->setColor(_color);
}

void Edge::selectAdjacentVertex()
{
    he1->getVertex()->select(true);
    he2->getVertex()->select(true);

    selected = false;
}

void Edge::selectAdjacentEdge()
{
    HalfEdge *scan = he2->getNext();
    do{
        Edge *e = scan->getEdge();
        e->select(true);

        scan = scan->getTwin()->getNext();
    }while( scan != he1 );

    scan = he1->getNext();
    do{
        Edge *e = scan->getEdge();
        e->select(true);

        scan = scan->getTwin()->getNext();
    }while( scan != he2 );
}

void Edge::selectAdjacentFace()
{
    Face *f = he1->getLoop()->getFace();
    f->select(true);

    f = he2->getLoop()->getFace();
    f->select(true);

    selected = false;
}
